package com.adingxiong.cft.aop;

import com.adingxiong.cft.annotate.Mylog;
import com.adingxiong.cft.config.ApplicationProperties;
import com.adingxiong.cft.entity.SysLog;
import com.adingxiong.cft.service.ISysLogService;
import com.adingxiong.cft.util.IpUtils;
import com.adingxiong.cft.util.JwtTokenUtil;
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @ClassName LoginLogAspect
 * @Description  操作日志切入面
 * @Author xiongchao
 * @Date 2020/9/27 10:22
 **/
@Aspect
@Component
public class SysLogAspect {

    @Autowired
    private ISysLogService logService;

    @Autowired
    private ApplicationProperties properties;

    @Autowired
    private JwtTokenUtil util;

    //定义切点 @Pointcut
    //在注解的位置切入代码
    @Pointcut("@annotation( com.adingxiong.cft.annotate.Mylog)")
    public void logPoinCut() {

    }

    //切面 配置通知
    @AfterReturning("logPoinCut()")
    public void savaLog(JoinPoint joinpoin){

        SysLog sysLog = new SysLog();

        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinpoin.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();
        Mylog myLog = method.getAnnotation(Mylog.class);

        if(myLog != null){
            String value  = myLog.value();
            sysLog.setOperation(value);
        }

        //获取请求的类名
        String className = joinpoin.getTarget().getClass().getName();

        //获取请求的方法名
        String methodName = method.getName();
        sysLog.setMethodName(className + "." + methodName);

        HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();

        String token  = request.getHeader(properties.getTokenHeader());

        String authToken = token.substring(properties.getTokenHead().length());
        String username = util.getUserNameFromToken(authToken);

        sysLog.setUsername(username);

        String ip = IpUtils.getRealIp(request);
        sysLog.setIp(ip);

        //请求参数
        Object args [] = joinpoin.getArgs();
        String param = JSON.toJSONString(args);
        sysLog.setParamName(param);
        sysLog.setCreateTime(new Date());
        logService.save(sysLog);
    }

}
